package com.cogent.business.action.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.cogent.business.action.AbstractAction;
import com.cogent.business.helper.UserDomainHelper;
import com.cogent.business.helper.ValidatorHelper;
import com.cogent.common.util.Globals;
import com.cogent.common.util.MapUtil;
import com.cogent.dao.BussinessQueryHelper;
import com.cogent.dao.domain.Pagination;
import com.cogent.dao.domain.QueryParamDomain;
import com.cogent.dao.facade.BussinessDaoFacade;
import com.cogent.dao.type.QueryType;
import com.cogent.menu.cache.MenuCache;
import com.opensymphony.oscache.util.StringUtil;

public class SysRoleAction extends AbstractAction {
	private Logger _log = Logger.getLogger(SysRoleAction.class); 	
	private static final String RESOURCE_CODE = "SYS_ROLE";
	private final static String REC_RESOURCE_CODE = "SYS_ROLE_REC";
	
	public String list() {
		if(!UserDomainHelper.isAllow(ServletActionContext.getRequest(), RESOURCE_CODE, Globals.VIEW))
			return "noright";
		HashMap formMap = getFormMapWithUser();
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("rolename", MapUtil.getStringValue(formMap, "rolename"), QueryType.LEFTMATCH));
		queryList.add(new QueryParamDomain("status", "0"));
		Pagination pagination = bussinessFacade.queryPaged("sys_role", queryList, "", MapUtil.getIntValue(formMap, "page", 1)
				, MapUtil.getIntValue(formMap, "numperpage", Globals.getPageSize()));
		setResponseMsg("paginlist", pagination);
		setResponseMsg("formmap", formMap);
		
		return "list";
	}
	
	public String listrec() {
		if(!UserDomainHelper.isAllow(ServletActionContext.getRequest(), REC_RESOURCE_CODE, Globals.VIEW))
			return "noright";
		HashMap formMap = getFormMapWithUser();
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("rolename", MapUtil.getStringValue(formMap, "rolename"), QueryType.LEFTMATCH));
		queryList.add(new QueryParamDomain("status", "1"));
		Pagination pagination = bussinessFacade.queryPaged("sys_role", queryList, "", MapUtil.getIntValue(formMap, "page", 1)
				, MapUtil.getIntValue(formMap, "numperpage", Globals.getPageSize()));
		setResponseMsg("paginlist", pagination);
		setResponseMsg("formmap", formMap);
		
		return "listrec";
	}
	
	public String add() {
		HashMap formMap = getFormMapWithUser();
		if(!UserDomainHelper.isAllow(ServletActionContext.getRequest(), RESOURCE_CODE, Globals.SAVE))
			return "noright";
		setResponseMsg("formmap", formMap);
		return "add";
	}
	
	public String mod() {
		if(!UserDomainHelper.isAllow(ServletActionContext.getRequest(), RESOURCE_CODE, Globals.UPDATE))
			return "noright";
		HashMap formMap = getFormMapWithUser();
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("id", MapUtil.getStringValue(formMap, "id")));
		try{
			bussinessFacade.createConn();
			HashMap dataMap = bussinessFacade.getByID("sys_role", queryList);
			dataMap.put("PERMISSIONMAP", loadCurRolePersCode(bussinessFacade, MapUtil.getStringValue(dataMap, "id")));
			setResponseMsg("datamap", dataMap);
		}finally{
			bussinessFacade.closeConn();
		}
		setResponseMsg("formmap", formMap);		
		
		return "mod";
	}
	
	public String view() {
		if((!UserDomainHelper.isAllow(ServletActionContext.getRequest(), RESOURCE_CODE, Globals.VIEW)) && (!UserDomainHelper.isAllow(ServletActionContext.getRequest(), REC_RESOURCE_CODE, Globals.VIEW)))
			return "noright";
		HashMap formMap = getFormMapWithUser();
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("id", MapUtil.getStringValue(formMap, "id")));
		try{
			bussinessFacade.createConn();
			HashMap dataMap = bussinessFacade.getByID("sys_role", queryList);
			dataMap.put("PERMISSIONMAP", loadCurRolePersCode(bussinessFacade, MapUtil.getStringValue(dataMap, "id")));
			setResponseMsg("datamap", dataMap);
		}finally{
			bussinessFacade.closeConn();
		}
		setResponseMsg("formmap", formMap);		
		
		return "view";
	}
	
	public String save() {
		if((!UserDomainHelper.isAllow(ServletActionContext.getRequest(), RESOURCE_CODE, Globals.SAVE)) && (!UserDomainHelper.isAllow(ServletActionContext.getRequest(), RESOURCE_CODE, Globals.UPDATE)))
			return "noright";
		HashMap formMap = getFormMapWithUser();
		if(MapUtil.isEmpty(formMap, "status"))
			formMap.put("status", "0");
		String errmsg = ValidatorHelper.validator("SysRoleForm", formMap);
		if(!StringUtil.isEmpty(errmsg)) {
			setNoteMsg("SysRoleForm", errmsg);
			setSessionInfo("formmap", formMap);
			setResponseUrl(formMap, "SysRole_mod.action");
			return null;
		}
		try{
			bussinessFacade.createConn();
			bussinessFacade.beginTran();
			String roleid = bussinessFacade.saveOrUpdate("sys_role", formMap);
			List allpersList = formToList(formMap, roleid);
			HashMap allidMap = loadCurRolePers(bussinessFacade, roleid);
			Iterator it = allpersList.iterator();
			while(it.hasNext()) {
				HashMap persMap = (HashMap)it.next();
				bussinessFacade.saveOrUpdate("sys_rolepermission", persMap);
				String curid = MapUtil.getStringValue(persMap, "id");
				if(allidMap.containsKey(curid))
					allidMap.remove(curid);
			}
			if(allidMap.size() > 0) {
				String curids = "";
				Iterator it2 = allidMap.keySet().iterator();
				while(it2.hasNext()) 
					curids += it2.next().toString() + ",";
				if(curids.length() > 0)
					curids = curids.substring(0, curids.length()-1);
				List delList = new ArrayList();
				delList.add(new QueryParamDomain("id", curids, QueryType.INARRAY));
				bussinessFacade.delete("sys_rolepermission", delList);
			}
			bussinessFacade.commitTran();
			 
			BussinessQueryHelper.removeByKey("sys_role");
			setResponseUrl(formMap, "SysRole_list.action");
		}catch(Exception ex) {
			_log.error(ex);
			bussinessFacade.rollbackTran();
			setSessionInfo("formmap", formMap);
			setResponseUrl(formMap, "SysRole_mod.action");
		}finally{
			bussinessFacade.closeConn();
		}
		
		return null;
	}
	
	public String recycle() {
		if(!UserDomainHelper.isAllow(ServletActionContext.getRequest(), RESOURCE_CODE, Globals.RECYCLE))
			return "noright";
		HashMap formMap = getFormMapWithUser();
		HashMap dataMap = new HashMap();
		dataMap.put("id", MapUtil.getStringValue(formMap, "id"));
		dataMap.put("modifier", MapUtil.getStringValue(formMap, "modifier"));
		dataMap.put("modifydate", MapUtil.getStringValue(formMap, "modifydate"));
		dataMap.put("status", "1");
		bussinessFacade.update("sys_role", dataMap);
		BussinessQueryHelper.removeByKey("sys_role");
		setResponseUrl(formMap, "SysRole_list.action");
		
		return null;
	}
	
	public String resume() {
		if(!UserDomainHelper.isAllow(ServletActionContext.getRequest(), REC_RESOURCE_CODE, Globals.RESUME))
			return "noright";
		HashMap formMap = getFormMapWithUser();
		HashMap dataMap = new HashMap();
		dataMap.put("id", MapUtil.getStringValue(formMap, "id"));
		dataMap.put("modifier", MapUtil.getStringValue(formMap, "modifier"));
		dataMap.put("modifydate", MapUtil.getStringValue(formMap, "modifydate"));
		dataMap.put("status", "0");
		bussinessFacade.update("sys_role", dataMap);
		setResponseUrl(formMap, "SysRole_listrec.action");
		
		return null;
	}
	
	public HashMap loadCurRolePers(BussinessDaoFacade bussinessFacade, String roleid) {
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("roleid", roleid));
		List valueList = bussinessFacade.query("sys_rolepermission", queryList);
		HashMap retMap = new HashMap();
		Iterator it = valueList.iterator();
		while(it.hasNext()) {
			HashMap datamap = (HashMap)it.next();
			retMap.put(MapUtil.getStringValue(datamap, "id"), "");
		}
		
		return retMap;
	}
	
	public HashMap loadCurRolePersCode(BussinessDaoFacade bussinessFacade, String roleid) {
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("roleid", roleid));
		List valueList = bussinessFacade.query("sys_rolepermission", queryList);
		HashMap retMap = new HashMap();
		Iterator it = valueList.iterator();
		while(it.hasNext()) {
			HashMap datamap = (HashMap)it.next();
			retMap.put(MapUtil.getStringValue(datamap, "resourcecode"), datamap);
		}
		
		return retMap;
	}
	
	private List formToList(HashMap formMap, String roleid) {
		List retList = new ArrayList();
		List allmenulist = MenuCache.getAllMenuList();
		int num = allmenulist.size();
		for(int i=0; i<num; i++) {
			int pervalue = getPersValue(formMap, i);
			if(pervalue > 0) {
				HashMap curMap = new HashMap();
				String id = MapUtil.getStringValue(formMap, "id_" + i);
				curMap.put("id", id);
				curMap.put("roleid", roleid);
				curMap.put("resourcecode", MapUtil.getStringValue(formMap, "key_" + i));
				curMap.put("permissioncode", "" + pervalue);
				if(StringUtil.isEmpty(id)) {
					curMap.put("modifier", MapUtil.getStringValue(formMap, "creator"));
					curMap.put("modifydate", MapUtil.getStringValue(formMap, "credate"));
				}
				curMap.put("modifier", MapUtil.getStringValue(formMap, "modifier"));
				curMap.put("modifydate", MapUtil.getStringValue(formMap, "modifydate"));
				retList.add(curMap);
			}
		}
		
		return retList;
	}
	
	private int getPersValue(HashMap formMap, int num) {
		int pervalue = 0;
		for(int i=0; i<7; i++) {
			if(MapUtil.getStringValue(formMap, "val_" + num + "_" + i).equals("true"))
				pervalue += (int)Math.pow(2, i);
		}
		
		return pervalue;
	}
}
